//
//  ZallFilterTableView.m
//  ZJS-DRIVER
//
//  Created by zxx on 2017/3/30.
//  Copyright © 2017年 zall. All rights reserved.
//

#import "ZallFilterTableView.h"
#import "ZallFilterTableViewCell.h"
#import "ZallBorderView.h"

@interface ZallFilterTableView()<UITableViewDelegate,UITableViewDataSource>

@property(strong, nonatomic) ZallBorderView *filterView;
@property(assign, nonatomic) CGFloat filterViewButtonWidth;
@property(strong, nonatomic) UITableView *tableView;
@property(assign, nonatomic) int selectedIndex;//-1表示没有选中

@end

static NSString *cellIdentity = @"ZallFilterTableViewCellIdentity";

@implementation ZallFilterTableView

#pragma mark - life cycle
- (instancetype)init{
    self = [self initWithFrame:CGRectZero];
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //-1表示没有选中
        self.filterButtonHeight = 44;
        _selectedIndex = -1;
        [self setUpViews];
    }
    return self;
}

- (void)setUpViews{
    [self addSubview:self.filterView];
    [self addSubview:self.tableView];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.filterView.frame = CGRectMake(0, 0, self.width, self.filterButtonHeight);
}

#pragma mark -setter
- (void)setDataSourceArr:(NSMutableArray *)dataSourceArr{
    _dataSourceArr = dataSourceArr;
    //刷新头部筛选选择视图
    [self reloadFilterView];
}

/**
 *  设置第dataSourceIndex的内容
 */
- (void)setData:(NSDictionary *)data dataSourceIndex:(NSUInteger)dataSourceIndex{
    NSMutableArray *tempDataSource = [_dataSourceArr mutableCopy];
    tempDataSource[dataSourceIndex] = data;
    _dataSourceArr = [tempDataSource copy];
    //刷新头部筛选选择视图
    [self reloadFilterView];
}

- (void)setTableViewSize:(CGSize)tableViewSize{
    _tableViewSize = tableViewSize;
    [self setNeedsLayout];
}

/**
 *  @brief  刷新头部筛选选择视图
 */
- (void)reloadFilterView{
    //先删除filterViewa上所有子视图
    [self.filterView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    if (!_dataSourceArr || _dataSourceArr.count == 0) {
        return;
    }
    _filterViewButtonWidth =  (ScreenWidth - _dataSourceArr.count - 1)/(_dataSourceArr.count*1.0);
    UIView *tempMarginView;
    for (int i = 0; i < _dataSourceArr.count; i++) {
        NSDictionary *dic = [_dataSourceArr safeObjectAtIndex:i];
        UIButton *filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [filterButton setTitle:dic[@"title"] forState:UIControlStateNormal];
        [filterButton setTitleColor:UIColorFromHexRGB(0x666666) forState:UIControlStateNormal];
        [filterButton setTitleColor:UIColorFromHexRGB(0x2eb6aa) forState:UIControlStateSelected];
        [filterButton setImage:[UIImage imageNamed:@"filter_down"] forState:UIControlStateNormal];
        [filterButton setImage:[UIImage imageNamed:@"filter_up"] forState:UIControlStateSelected];
        NSString *title = dic[@"title"];
        CGSize titleSize = [title stringSizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToWidth:_filterViewButtonWidth];
        [filterButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width + 5, 0, (titleSize.width + 5) * -1)];
        [filterButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -9, 0, 9)];
        filterButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
        filterButton.tag = 1000 + i;
        [filterButton addTarget:self action:@selector(filterButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        filterButton.frame = CGRectMake(tempMarginView?tempMarginView.right:0, 0, _filterViewButtonWidth, _filterButtonHeight);
        [self.filterView addSubview:filterButton];
        if (_dataSourceArr.count > 1 && i < _dataSourceArr.count - 1) {
            UIView *marginView = [[UIView alloc] init];
            marginView.backgroundColor = UIColorFromHexRGB(0xf0f0f0);
            marginView.frame = CGRectMake(filterButton.right, (_filterButtonHeight-17)/2.0, 1, 17);
            [self.filterView addSubview:marginView];
            tempMarginView = marginView;
        }
    }
}

/**
 *  @brief  设置selectedIndex
 *  动态折叠/展开tableView
 */
- (void)setSelectedIndex:(int)selectedIndex{
    _selectedIndex = selectedIndex;
    if (_selectedIndex < 0) {//当selectedIndex < 0，折叠tableView
        [self.tableView reloadData];
        self.tableView.height = 0;
        self.height = self.filterView.bottom;
    }else{//当selectedIndex >= 0,展开tableView
        self.tableView.frame = CGRectMake(0, self.filterView.bottom, self.width, self.tableViewSize.height);
        self.height = self.tableView.bottom;
        [self.tableView reloadData];
    }
}

#pragma mark - getter
- (ZallBorderView *)filterView{
    if (_filterView) {
        return _filterView;
    }
    _filterView = [[ZallBorderView alloc] init];
    _filterView.backgroundColor = [UIColor whiteColor];
    _filterView.borderLineWidth = 1;
    _filterView.borderColor = UIColorFromHexRGB(0xdddddd);
    _filterView.borderStyle = ZallBorderLineTop | ZallBorderLineBottom;
    return _filterView;
}

- (UITableView *)tableView{
    if (_tableView) {
        return _tableView;
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithRed:120/255.0 green:120/255.0 blue:122/255.0 alpha:0.5];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.bounces = NO;
    _tableView.tableFooterView = [UIView new];
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    [_tableView registerClass:[ZallFilterTableViewCell class] forCellReuseIdentifier:cellIdentity];
    return _tableView;
}

#pragma mark - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selectedIndex < 0) {
        return 0;
    }
    NSDictionary *dic = [_dataSourceArr safeObjectAtIndex:self.selectedIndex];
    NSArray *dataSource = dic[@"dataSource"];
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectedIndex < 0) {
        return [[UITableViewCell alloc] init];
    }
    NSDictionary *dic = [_dataSourceArr safeObjectAtIndex:self.selectedIndex];
    NSArray *dataSource = dic[@"dataSource"];
    NSDictionary *dataSourceDic = [dataSource safeObjectAtIndex:indexPath.row];
    UIButton *filterButton = [self.filterView viewWithTag:1000 + self.selectedIndex];
    NSString *filterTitle = @"";
    if (filterButton) {
        filterTitle = filterButton.titleLabel.text;
    }
    ZallFilterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity forIndexPath:indexPath];
    cell.contentTextLabel.text = dataSourceDic[@"title"];
    if ([filterTitle isEqualToString:dataSourceDic[@"title"]]) {
        cell.contentTextLabel.textColor = UIColorFromHexRGB(0x2eb6aa);
    }else{
        cell.contentTextLabel.textColor = UIColorFromHexRGB(0x222222);
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dic = [_dataSourceArr safeObjectAtIndex:self.selectedIndex];
    NSArray *dataSource = dic[@"dataSource"];
    NSDictionary *dataSourceDic = [dataSource safeObjectAtIndex:indexPath.row];
    UIButton *filterButton = [self.filterView viewWithTag:1000 + self.selectedIndex];
    if (filterButton) {
        NSString *title = dataSourceDic[@"title"];
        [filterButton setTitle:title forState:UIControlStateNormal];
        CGSize titleSize = [title stringSizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToWidth:_filterViewButtonWidth];
        [filterButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width + 5, 0, (titleSize.width + 5) * -1)];
        [filterButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -9, 0, 9)];
    }
    //block回调
    if (_filterBlock) {
        _filterBlock(self.selectedIndex,indexPath.row,dataSourceDic[@"value"]);
    }
    self.selectedIndex = -1;
    for (UIView  *view in self.filterView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *tempButton = (UIButton *)view;
            tempButton.selected = NO;
        }
    }
    
}

#pragma mark - private methods
- (void)filterButtonClicked:(UIButton *)button{
    //取消其他按钮的选中状态
    for (UIView  *view in self.filterView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *tempButton = (UIButton *)view;
            if (![tempButton isEqual:button]) {
                tempButton.selected = NO;
            }
        }
    }
    button.selected = !button.isSelected;
    if (button.isSelected) {
        self.selectedIndex = (int)button.tag - 1000;
        if (_filterButtonClickBlock) {
            _filterButtonClickBlock(button.tag - 1000,NO);
        }
    }else{
        self.selectedIndex = -1;
        if (_filterButtonClickBlock) {
            _filterButtonClickBlock(button.tag - 1000,YES);
        }
    }
    
}

/**
 *  折叠筛选选择视图
 */
- (void)floldFilterTableView{
    self.selectedIndex = -1;
    //取消其他按钮的选中状态
    for (UIView  *view in self.filterView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *tempButton = (UIButton *)view;
            tempButton.selected = NO;
        }
    }
}

/**
 *  设置第index个按钮的文案
 */
- (void)setButtonText:(NSString *)text index:(NSUInteger)index{
    UIButton *filterButton = [self.filterView viewWithTag:1000 + index];
    if (filterButton) {
        [filterButton setTitle:text forState:UIControlStateNormal];
        CGSize titleSize = [text stringSizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToWidth:_filterViewButtonWidth];
        [filterButton setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width + 5, 0, (titleSize.width + 5) * -1)];
        [filterButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -9, 0, 9)];

    }
}

/**
 *  获取第index个按钮的文案
 */
- (NSString *)getButtonTextWithIndex:(NSUInteger)index{
    UIButton *filterButton = [self.filterView viewWithTag:1000 + index];
    if (filterButton) {
        return filterButton.titleLabel.text;
        
    }
    return @"";
}

@end
